package com.woniu108.product.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.carService.commos.dto.AdminInfoDto;
import com.woniu108.carService.commos.dto.ProductInfoDto;
import com.woniu108.carService.commos.dto.UserCartDto;
import com.woniu108.carService.commos.dto.UserInfoDto;
import com.woniu108.carService.commos.exception.admin.AdminException;
import com.woniu108.carService.commos.exception.admin.AdminExceptionCode;
import com.woniu108.carService.commos.exception.produnt.ProductException;
import com.woniu108.carService.commos.exception.produnt.ProductExceptionCode;
import com.woniu108.carService.commos.exception.upload.UpLoadException;
import com.woniu108.carService.commos.exception.upload.UpLoadExceptionCode;
import com.woniu108.carService.commos.util.*;
import com.woniu108.product.client.PersonClient;
import com.woniu108.product.mapper.*;
import com.woniu108.product.model.*;
import com.woniu108.product.param.*;
import com.woniu108.product.service.ProductInfoService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 商品详情表 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements ProductInfoService {
    @Resource
    private ProductInfoMapper productInfoMapper;
    @Resource
    private ProductItemMapper productItemMapper;
    @Resource
    private ProductBrandMapper productBrandMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OSSUtil ossUtil;
    @Resource
    private PersonClient personClient;
    @Resource
    private ProductActiveMapper productActiveMapper;

    /**
     * @param image 图片文件
     * @return string 图片地址
     * @throws Exception 自定义异常
     */
    private String handleImageUpload(MultipartFile image) throws Exception {
        // 判断文件类型
        System.out.println("image:"+image);
        if (!FileUtil.isImageFile(image.getInputStream())) {
            throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_ERROR);
        }

        String oldName = image.getOriginalFilename();
        if (oldName == null) {
            throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_NULL);
        }

        int lastIndex = oldName.lastIndexOf(".");
        if (lastIndex == -1) {
            throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_LACK_SUFFIX);
        }
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString();

        return ossUtil.uploadFile(image.getInputStream(), fileName + suffix, "class108");
    }

    /**
     * 判断管理员
     */
    private void isAdmin(String adminId) {
        // 检查 adminId 是否为 null
        if (adminId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断管理员权限
        AdminInfoDto adminInfo = personClient.getByAdminId(adminId).getData();
        if (adminInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
        if (adminInfo.getAdminRoleId() != 1) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_PERMISSION);
        }
    }


    /**
     * 判断用户
     */
    private void isUser(String userId) {
        // 检查 userId 是否为 null
        if (userId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断用户
        UserInfoDto userInfo = personClient.getByUserId(userId).getData();
        if (userInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
    }


    /**
     * 将infos转为dto对象
     */
    private List<ProductInfoDto> infosToDtos(List<ProductInfo> infos) {
        //设dto集合
        ArrayList<ProductInfoDto> dtos = new ArrayList<>();
        //将infos转化为dto对象
        for (ProductInfo info : infos) {
            //复制信息
            ProductInfoDto dto = BeanUtil.toBean(info, ProductInfoDto.class);
            //通过商品编号查商品
            ProductItem item = productItemMapper.selectById(dto.getPItemId());
            dto.setPName(item.getPName());
            //查种类名
            ProductType type = productTypeMapper.selectById(item.getPTId());
            dto.setPTName(type.getPTName());
            //查品牌名
            ProductBrand brand = productBrandMapper.selectById(item.getPBId());
            dto.setPBName(brand.getPBName());
            //查折扣
            QueryWrapper<ProductActive> wrapper = new QueryWrapper<>();
            wrapper.eq("p_item_id", item.getPItemId());
            ProductActive active = productActiveMapper.selectOne(wrapper);
            //没有活动则不加载
            if(active!=null) {
                dto.setCutDownPercent(active.getCutDownPercent());
            }
            //加入集合
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public List<ProductInfoDto> findAllProductInfo(FindAllProductInfoParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        //查询
        QueryWrapper<ProductInfo> wrapper = new QueryWrapper<>();
        //判断带不带总览id
        if (param.getPItemId() != null) {
            wrapper.eq("p_item_id", param.getPItemId());
        }
        //根据状态
        wrapper.ne("p_info_state", StaticData.PRODUCT_INFO_STATE_DELETE);
        List<ProductInfo> infos = productInfoMapper.selectList(wrapper);
        //将infos转化为dto对象
        return infosToDtos(infos);
    }

    @Override
    public List<ProductInfoDto> findAllNormalProductInfo(Integer pItemId) {

        //查询
        QueryWrapper<ProductInfo> wrapper = new QueryWrapper<>();
        //判断带不带总览id
        if (pItemId != null) {
            wrapper.eq("p_item_id",pItemId);
        }
        //根据状态
        wrapper.eq("p_info_state", StaticData.PRODUCT_INFO_STATE_NORMAL);
        List<ProductInfo> infos = productInfoMapper.selectList(wrapper);
        //将infos转化为dto对象
        return infosToDtos(infos);
    }

    @Override
    public Boolean insertProductInfo(InsertProductInfoParam param) throws Exception {
        //判断管理员权限
        isAdmin(param.getAdminId());
        //图片转string
        String pPicture =handleImageUpload(param.getPPicture());
        //查该商品名是否存在
        QueryWrapper<ProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("p_info_name", param.getPInfoName());
        ProductInfo selectOne = productInfoMapper.selectOne(wrapper);
        //判断该商品存在和状态
        if (selectOne != null) {
            if (Objects.equals(selectOne.getPInfoState(), StaticData.PRODUCT_INFO_STATE_BAN) || Objects.equals(selectOne.getPInfoState(), StaticData.PRODUCT_INFO_STATE_NORMAL)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_HAVE);
            }
            //将删除状态改为正常
            selectOne.setPInfoState(StaticData.PRODUCT_INFO_STATE_NORMAL);
            // 设置 param 中的值给 selectOne
            selectOne.setPItemId(param.getPItemId());
            selectOne.setPInfoPrice(param.getPInfoPrice());
            selectOne.setRestNum(param.getRestNum());
            selectOne.setPDetails(param.getPDetails());
            selectOne.setPPicture(pPicture);
            selectOne.setFreezeNum(BigDecimal.valueOf(0));
            selectOne.setPInfoSum(0);
            selectOne.setCreateTime(LocalDateTime.now());
            int i = productInfoMapper.updateById(selectOne);
            return i > 0;
        }
        // 如果 selectOne 为空，创建一个新的 ProductInfo 对象
        ProductInfo info = BeanUtil.toBean(param, ProductInfo.class);
        info.setFreezeNum(BigDecimal.valueOf(0));
        info.setPPicture(pPicture);
        info.setPInfoSum(0);
        info.setCreateTime(LocalDateTime.now());
        info.setPInfoState(StaticData.PRODUCT_INFO_STATE_NORMAL);
        int insert = productInfoMapper.insert(info);
        return insert > 0;
    }

    @Override
    public Boolean updateProductInfo(UpdateProductInfoParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        //通过id查商品
        ProductInfo info = productInfoMapper.selectById(param.getPInfoId());
        if (info == null || Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        //通过名字查，看新名字是否同名
        if (param.getPInfoName() != null) {
            QueryWrapper<ProductInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("p_info_name", param.getPInfoName());
            ProductInfo selectOne = productInfoMapper.selectOne(wrapper);
            if (selectOne != null) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_HAVE);
            }
            //修改名字
            info.setPInfoName(param.getPInfoName());
        }

        //修改价格
        if (param.getPInfoPrice() != null) {
            info.setPInfoPrice(param.getPInfoPrice());
        }
        //修改库存
        if (param.getRestNum() != null) {
            info.setRestNum(param.getRestNum());
        }
        //修改描述
        if (param.getPDetails() != null) {
            info.setPDetails(param.getPDetails());
        }
        int i = productInfoMapper.updateById(info);
        return i > 0;

    }

    @Override
    public Boolean updateProductPicture(UpdateProductPictureParam param) throws Exception {
        //判断管理员
        isAdmin(param.getAdminId());
        //图片转string
        String pPicture = handleImageUpload(param.getPPicture());
        //通过id查商品
        ProductInfo info = productInfoMapper.selectById(param.getPInfoId());
        //判断该id商品是否存在
        if (info == null || Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_HAVE);
        }
        //修改照片地址
        info.setPPicture(pPicture);
        //修改数据库
        int i = productInfoMapper.updateById(info);
        return i > 0;
    }

    @Override
    public Boolean banProductInfo(BanProductInfoParam param) {

        //判断管理员
        isAdmin(param.getAdminId());
        for (Integer pInfoId : param.getPInfoIds()) {
            //禁用商品详情
            ProductInfo productInfo = productInfoMapper.selectById(pInfoId);
            // 判断是否存在和状态
            if (productInfo == null) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
            }

            if (Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
            }

            if (Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_BAN)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_BANED);
            }
            //禁用
            productInfo.setPInfoState(StaticData.PRODUCT_INFO_STATE_BAN);
            productInfoMapper.updateById(productInfo);
        }
        return true;
    }

    @Override
    public Boolean unlockProductInfo(UnlockProductInfoParam param) {
        // 判断管理员权限
        isAdmin(param.getAdminId());

        for (Integer pInfoId : param.getPInfoIds()) {
            // 查找商品详情
            ProductInfo productInfo = productInfoMapper.selectById(pInfoId);

            // 判断商品详情是否存在和状态
            if (productInfo == null || Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
            }

            if (Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_NORMAL)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_STATE_NORMAL);
            }
            //查询商品总览状态
            ProductItem productItem = productItemMapper.selectById(productInfo.getPItemId());
            //判断是否存在和状态
            if (productItem == null || Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
            }
            if (Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_BAN)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_BANED);
            }
            // 解锁（将状态设置为正常）
            productInfo.setPInfoState(StaticData.PRODUCT_INFO_STATE_NORMAL);
            productInfoMapper.updateById(productInfo);
        }
        return true;
    }

    @Override
    public Boolean deleteProductInfo(DeleteProductInfoParam param) {
        // 判断管理员权限
        isAdmin(param.getAdminId());

        for (Integer pInfoId : param.getPInfoIds()) {
            // 查找商品详情
            ProductInfo productInfo = productInfoMapper.selectById(pInfoId);

            // 判断商品详情是否存在和状态
            if (productInfo == null || Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
            }
            // 删除
            productInfo.setPInfoState(StaticData.PRODUCT_INFO_STATE_DELETE);
            productInfoMapper.updateById(productInfo);
        }
        return true;
    }

    @Override
    public Boolean successfulSale(SuccessfulSaleParam param) {
        // 查找商品详情
        ProductInfo productInfo = productInfoMapper.selectById(param.getPInfoId());

        // 判断商品详情是否存在和状态
        if (productInfo == null || Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        //交易成功减少冻结量
        productInfo.setFreezeNum(productInfo.getFreezeNum().subtract(BigDecimal.valueOf(param.getNum())));
        //修改数据库
        int i = productInfoMapper.updateById(productInfo);
        return i > 0;
    }

    @Override
    public Boolean failedSale(FailedSaleParam param) {
        // 查找商品详情
        ProductInfo productInfo = productInfoMapper.selectById(param.getPInfoId());

        // 判断商品详情是否存在和状态
        if (productInfo == null || Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        //交易失败，增加余量
        productInfo.setRestNum(productInfo.getRestNum().add(BigDecimal.valueOf(param.getNum())));
        //修改数据库
        int i = productInfoMapper.updateById(productInfo);
        return i > 0;
    }

    @Override
    public Boolean addPInfoNum(Integer pInfoId) {
        // 检查 pInfoId 是否为 null
        if (pInfoId == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_ID_NULL);
        }
        // 根据 pInfoId 查询 ProductInfo
        ProductInfo info = productInfoMapper.selectById(pInfoId);
        // 检查 info 是否存在以及状态是否为已删除
        if (Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        // 增加 PInfoSum
        info.setPInfoSum(info.getPInfoSum() + 1);
        // 更新数据库中的 ProductInfo
        int i = productInfoMapper.updateById(info);
        // 返回是否更新成功
        return i > 0;
    }

    @Override
    public Boolean reducePInfoNum(Integer pInfoId) {
        // 检查 pInfoId 是否为 null
        if (pInfoId == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_ID_NULL);
        }
        // 根据 pInfoId 查询 ProductInfo
        ProductInfo info = productInfoMapper.selectById(pInfoId);
        // 检查 info 是否存在以及状态是否为已删除
        if (info == null || Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        // 减少 PInfoSum
        info.setPInfoSum(Math.max(0, info.getPInfoSum() - 1));
        // 更新数据库中的 ProductInfo
        int i = productInfoMapper.updateById(info);
        // 返回是否更新成功
        return i > 0;
    }

    @Override
    public Boolean addGoodsToCart(AddGoodsToCartParam param) throws Exception {
        // 检查 pInfoId 是否为 null
        if (param.getPInfoId() == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_ID_NULL);
        }
        //查询商品信息
        ProductInfo info = productInfoMapper.selectById(param.getPInfoId());
        // 检查 info 是否存在以及状态是否为已删除
        if (info == null || Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_BAN)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_BANED);
        }
        //判断当前用户购物车列表中是否存在该商品
        if (redisUtil.zscore(RedisKey.userCart(param.getUserId()), param.getPInfoId().toString()) == null) {
            //首次添加
            //向购物车列表中添加该商品id
            redisUtil.zadd(RedisKey.userCart(param.getUserId()), param.getPInfoId().toString(), System.currentTimeMillis());
            //向redis新增hash数据，保存完整的购物车信息
            try {
                //新增商品数据
                HashMap<String, Object> map = new HashMap<>(16);
                map.put("pInfoId", info.getPInfoId().toString());
                map.put("pInfoName", info.getPInfoName());
                map.put("pItemId", info.getPItemId().toString());
                map.put("pInfoPrice", info.getPInfoPrice().toString());
                map.put("pDetails", info.getPDetails());
                map.put("pPicture", info.getPPicture());
                map.put("cartNumber", param.getNumber().toString());
                redisUtil.hmset(RedisKey.userCartGoods(param.getUserId(), param.getPInfoId()), map);
            } catch (Exception e) {
                redisUtil.zsrem(RedisKey.userCart(param.getUserId()), param.getPInfoId().toString());
            }
        } else {
            redisUtil.hincrby(RedisKey.userCartGoods(param.getUserId(), param.getPInfoId()), "cartNumber", param.getNumber());
        }
        return true;
    }

    @Override
    public Boolean updateGoodsNumber(UpdateGoodsNumberParam param) throws Exception {
        //查询商品信息
        ProductInfo info = productInfoMapper.selectById(param.getPInfoId());
        // 检查 info 是否存在以及状态是否为已删除
        if (info == null || Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_BAN)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_BANED);
        }
        //判断当前用户购物车列表中是否存在该商品
        if (redisUtil.zscore(RedisKey.userCart(param.getUserId()), param.getPInfoId().toString()) == null) {
            //说明购物车中不存在该商品
            throw new ProductException(ProductExceptionCode.PRODUCT_CART_NOT_HAVE);
        }
        //判断修改数量
        if (param.getCartNumber() == 0) {
            //说明删除这个商品
            redisUtil.zsrem(RedisKey.userCart(param.getUserId()), param.getPInfoId().toString());
            redisUtil.delete(RedisKey.userCartGoods(param.getUserId(), param.getPInfoId()));
        }
        //修改商品数量
        redisUtil.hmset1(RedisKey.userCartGoods(param.getUserId(), param.getPInfoId()), "cartNumber", param.getCartNumber().toString());
        return true;
    }

    @Override
    public Boolean deleteProductInCart(Integer pInfoId, String userId) throws Exception {
        //查询商品信息
        ProductInfo info = productInfoMapper.selectById(pInfoId);
        // 检查 info 是否存在以及状态是否为已删除
        if (info == null || Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_BAN)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_BANED);
        }
        //判断当前用户购物车列表中是否存在该商品
        if (redisUtil.zscore(RedisKey.userCart(userId), pInfoId.toString()) == null) {
            //说明购物车中不存在该商品
            throw new ProductException(ProductExceptionCode.PRODUCT_CART_NOT_HAVE);
        }
        redisUtil.zsrem(RedisKey.userCart(userId), pInfoId.toString());
        redisUtil.delete(RedisKey.userCartGoods(userId, pInfoId));
        return true;
    }

    @Override
    public List<UserCartDto> findUserCart(String userId) {
        // 查询购物车中的商品ID集合
        Set<String> set = redisUtil.zreverange(RedisKey.userCart(userId), 0, -1);
        ArrayList<UserCartDto> dtos = new ArrayList<>();
        // 遍历购物车中的商品ID集合
        for (String infoId : set) {
            // 获取购物车中单个商品的信息
            Map<Object, Object> map = redisUtil.hgetall(RedisKey.userCartGoods(userId, Integer.parseInt(infoId)));
            Integer id = null;
            Integer cartNumber = null;
            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                Object key = entry.getKey();
                Object value = entry.getValue();
                if ("pInfoId".equals(key)) {
                    if (value instanceof Integer) {
                        id = (Integer) value;
                    } else if (value instanceof String) {
                        id = Integer.parseInt((String) value);
                    }
                } else if ("cartNumber".equals(key)) {
                    if (value instanceof Integer) {
                        cartNumber = (Integer) value;
                    } else if (value instanceof String) {
                        cartNumber = Integer.parseInt((String) value);
                    }
                }
            }
            //查商品Id对应商品信息
            ProductInfo info = productInfoMapper.selectById(id);
            //复制信息
            UserCartDto dto = BeanUtil.toBean(info, UserCartDto.class);
            //查item信息
            ProductItem item = productItemMapper.selectById(info.getPItemId());
            dto.setPName(item.getPName());
            //查品牌信息
            ProductBrand brand = productBrandMapper.selectById(item.getPBId());
            dto.setPBName(brand.getPBName());
            //查种类信息
            ProductType type = productTypeMapper.selectById(item.getPTId());
            dto.setPTName(type.getPTName());
            //修改数量
            dto.setCartNumber(cartNumber);
            //加入集合
            dtos.add(dto);

        }
        return dtos;
    }

    @Override
    public Boolean successfulOrder(SuccessfulOrderParam param) {
        // 查找商品详情
        ProductInfo productInfo = productInfoMapper.selectById(param.getPInfoId());

        // 判断商品详情是否存在和状态
        if (productInfo == null || Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        if (productInfo.getRestNum().compareTo(BigDecimal.valueOf(param.getNum())) < 0) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_REST_NUM_NOT_HAVE);
        }
        //下单成功增加冻结量
        productInfo.setFreezeNum(productInfo.getFreezeNum().add(BigDecimal.valueOf(param.getNum())));
        //下单成功减少余量
        productInfo.setRestNum(productInfo.getRestNum().subtract(BigDecimal.valueOf(param.getNum())));
        //修改数据库
        int i = productInfoMapper.updateById(productInfo);
        return i > 0;
    }

    @Override
    public ProductInfoDto findProductInfoById(Integer pInfoId) {
        ProductInfo info = productInfoMapper.selectById(pInfoId);
        ArrayList<ProductInfo> infos = new ArrayList<>();
        infos.add(info);
        List<ProductInfoDto> dtos = infosToDtos(infos);
        return dtos.get(0);
    }

    @Override
    public Boolean submitFreezeNum(FailedSaleParam param) {
        // 查找商品详情
        ProductInfo productInfo = productInfoMapper.selectById(param.getPInfoId());

        // 判断商品详情是否存在和状态
        if (productInfo == null || Objects.equals(productInfo.getPInfoState(), StaticData.PRODUCT_INFO_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_INFO_NOT_HAVE);
        }
        //交易失败，减少冻结量
        productInfo.setFreezeNum(productInfo.getFreezeNum().subtract(BigDecimal.valueOf(param.getNum())));
        //修改数据库
        int i = productInfoMapper.updateById(productInfo);
        return i > 0;
    }
}
